package com.choco.jsondb.reader;

import com.alibaba.fastjson.JSON;
import com.choco.jsondb.Context;
import com.choco.jsondb.utils.FileUtil;

import java.util.ArrayList;
import java.util.Map;

public class ArrayReader implements Reader{
    private Map<String, ArrayList<String>> map;

    public ArrayReader(Context context) {
        map = (Map<String, ArrayList<String>>) FileUtil.read(context);
    }

    @Override
    public String get(String key) {
        ArrayList<String> arrayList = map.get(key);
        return unescape(JSON.toJSONString(arrayList));
    }

    @Override
    public String getAll() {
        ArrayList<String> arrayList = new ArrayList<>();

        for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
            arrayList.addAll(entry.getValue());
        }

        return unescape(JSON.toJSONString(arrayList));
    }

    @Override
    public String get() {
        ArrayList<String> arrayList = map.get(Context.DEFAULT_KEY);
        return unescape(JSON.toJSONString(arrayList));
    }

    private String unescape(String str){
        return str.replaceAll("\\\\", "")
                .replaceAll("\"\\{", "{")
                .replaceAll("\\}\"", "}");
    }
}
